<template>
  <div class="point-type-management">
    <div class="category-container">
      <!-- 大类列表 -->
      <div class="big-category-list">
        <h2>功能</h2>
        <ul>
          <li
              v-for="category in categories"
              :key="category.id"
              @click="selectBigCategory(category)"
              :class="{ active: activeBigCategory?.id === category.id }"
          >
            {{ category.name }}
          </li>
          <li @click="addBigCategory">+ 新增功能</li>
        </ul>
      </div>

      <!-- 小类列表 -->
      <div class="small-category-list" v-if="activeBigCategory">
        <h2>功能细分</h2>
        <ul>
          <li
              v-for="smallCat in activeBigCategory.smallCategories"
              :key="smallCat.id"
              @click="selectSmallCategory(smallCat)"
              :class="{ active: activeSmallCategory?.id === smallCat.id }"
          >
            {{ smallCat.name }}
          </li>
          <li @click="addSmallCategory">+ 新增细分</li>
        </ul>
      </div>

      <!-- 点位列表 -->
      <div class="point-list" v-if="activeSmallCategory">
        <h2>点位列表</h2>
        <el-button type="primary" @click="addPoint">添加点位</el-button>
        <el-table
            :data="pointData"
            style="width: 100%"
            :row-class-name="tableRowClassName">
          <el-table-column
              prop="pointName"
              label="点位名称"
              >
          </el-table-column>
          <el-table-column
              prop="pointId"
              label="点位ID"
              >
          </el-table-column>
          <el-table-column
              prop="instance"
              label="点位ID"
          >
          </el-table-column>
          <el-table-column
              prop="status"
              label="状态">
          </el-table-column>
          <el-table-column
              label="操作">
            <template #default="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            background
            :hide-on-single-page="true"
            layout="prev, pager, next"
            :total="12">
        </el-pagination>
        <table>
          <thead>
          <tr>
            <th>ID</th>
            <th>名称</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="point in activeSmallCategory.points" :key="point.id">
            <td>{{ point.id }}</td>
            <td>{{ point.name }}</td>
            <td>{{ point.status }}</td>
            <td>
              <button @click="editPoint(point)">编辑</button>
              <button @click="deletePoint(point)">删除</button>
            </td>
          </tr>
          </tbody>
        </table>
        <button @click="addPoint">添加点位</button>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <PointEditDialog
        v-if="showEditDialog"
        :point="currentPoint"
        @save="savePoint"
        @close="closeEditDialog"
    />


    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        fullscreen
        :before-close="handleClose">
      <div class="dialog-container">
        <div class="dialog-left">
          <!--<el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" lazy></el-tree>-->
          <el-tree
              :props="treeProps"
              :load="loadNode"
              lazy
              highlight-current
              @node-click="handleNodeClick">
            <div slot-scope="{ node }" class="custom-tree-node">
              <span v-if="node.loading"><i class="el-icon-loading"></i></span>
              <span>{{ node.label }}</span>
            </div>
          </el-tree>
        </div>
        <div class="dialog-right">
          ceshi
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import PointEditDialog from './PointEditDialog.vue'
import {getTreeApi} from '@/api/point'
export default {
  components: {
    PointEditDialog
  },
  data() {
    return {
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: (data, node) => {
          // 可以根据业务需求自定义判断逻辑
          console.log("no",data, node)
          return false // 默认所有节点都可展开
        }
      },
      nodeCache: new Map(),
      data: [
      {
        label: '一级 1',
        children: [{
          label: '二级 1-1',
          children: [{
            label: '三级 1-1-1'
          }]
        }]
      }, {
        label: '一级 2',
        children: [{
          label: '二级 2-1',
          children: [{
            label: '三级 2-1-1'
          }]
        }, {
          label: '二级 2-2',
          children: [{
            label: '三级 2-2-1'
          }]
        }]
      }, {
        label: '一级 3',
        children: [{
          label: '二级 3-1',
          children: [{
            label: '三级 3-1-1'
          }]
        }, {
          label: '二级 3-2',
          children: [{
            label: '三级 3-2-1'
          }]
        }]
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialogVisible: false,
      categories: [
          {id: 1, name: '温度', smallCategories: [{id: 1, name: '温度1'}, {id: 2, name: '温度2'}]},
      ], // 从API获取或本地初始化
      activeBigCategory: null,
      activeSmallCategory: null,
      showEditDialog: false,
      currentPoint: null,
      pointData: [
        {
          id: 1,
          pointName: '转炉煤气总管瞬时流量',
          pointId: 12312412,
          instance: '全部分类/河南钢铁集团/周口钢铁公司/炼钢/能源计量/能源计量',
          status: '正常'
        },
        {
          id: 2,
          pointName: '转炉煤气总管瞬时流量',
          pointId: 12312412,
          instance: '全部分类/河南钢铁集团/周口钢铁公司/炼钢/能源计量/能源计量',
          status: '正常'
        },
        {
          id: 3,
          pointName: '转炉煤气总管瞬时流量',
          pointId: 12312412,
          instance: '全部分类/河南钢铁集团/周口钢铁公司/炼钢/能源计量/能源计量',
          status: '正常'
        },
        {
          id: 4,
          pointName: '转炉煤气总管瞬时流量',
          pointId: 12312412,
          instance: '全部分类/河南钢铁集团/周口钢铁公司/炼钢/能源计量/能源计量',
          status: '正常'
        },
      ],
    }
  },
  methods: {
    async loadNode(node, resolve) {
      const nodeId = node.level === 0 ? -1 : node.data.id

      // 检查缓存
      if (this.nodeCache.has(nodeId)) {
        return resolve(this.nodeCache.get(nodeId))
      }

      try {

        await getTreeApi(nodeId).then(response=>{
          const children = response.data.data || []
          console.log("打印", response.data)
          // 缓存数据
          this.nodeCache.set(nodeId, children)
          resolve(children)
        })


      } catch (error) {
        console.error('加载节点失败:', error)
        resolve([])
      }
    },

    handleNodeClick(data, node) {
      console.log('点击节点:', data, node)
      // 可以在这里处理节点点击事件
    },
    selectBigCategory(category) {
      this.activeBigCategory = category
      this.activeSmallCategory = null
    },
    selectSmallCategory(smallCat) {
      this.activeSmallCategory = smallCat
    },
    addBigCategory() {
      this.open("big");
      // const name = prompt('请输入大类名称')
      // if (name) {
      //   this.categories.push({
      //     id: Date.now(),
      //     name,
      //     smallCategories: []
      //   })
      // }
    },
    addSmallCategory() {
      if (!this.activeBigCategory) return
      this.open("small");
      // const name = prompt('请输入小类名称')
      // if (name) {
      //   this.activeBigCategory.smallCategories.push({
      //     id: Date.now(),
      //     name,
      //     points: []
      //   })
      // }
    },
    addPoint() {
      // 打开弹框
      this.dialogVisible = true;
      // 363750236425932800
      // 363750321465446400
      getTreeApi(363750321465446400).then(res=>{
        console.log("的", res.data);

        // const das = this.buildTree(res.data, "-1")
        // console.log("das", das)
        const da = this.convertToTree(res.data);
        console.log("-----------" , da)
        const map = {}
        const tree = []
        res.data.forEach(item=>{
          map[item.id] = {
            label: item.name,
            children: []
          }
        });
        console.log("dayi9n", map)
        res.data.forEach(item=>{
          if(item.parentId === '-1') {
            tree.push(map[item.id]);
          }else {
            const parent = map[item.parentId];
            if (parent) {
              parent.children.push(map[item.id]);
            }
          }
        })
        console.log("当前数", tree)
        // this.data = tree;
      })

      // if (!this.activeSmallCategory) return
      // this.currentPoint = {
      //   id: Date.now(),
      //   name: '',
      //   status: 'active'
      // }
      // this.showEditDialog = true
    },
    editPoint(point) {
      this.currentPoint = {...point}
      this.showEditDialog = true
    },
    deletePoint(point) {
      if (confirm(`确定删除点位 ${point.name} 吗?`)) {
        const index = this.activeSmallCategory.points.findIndex(p => p.id === point.id)
        if (index !== -1) {
          this.activeSmallCategory.points.splice(index, 1)
        }
      }
    },
    savePoint(updatedPoint) {
      if (!this.activeSmallCategory) return

      const index = this.activeSmallCategory.points.findIndex(p => p.id === updatedPoint.id)
      if (index === -1) {
        // 新增
        this.activeSmallCategory.points.push(updatedPoint)
      } else {
        // 更新
        this.activeSmallCategory.points.splice(index, 1, updatedPoint)
      }
      this.closeEditDialog()
    },
    closeEditDialog() {
      this.showEditDialog = false
      this.currentPoint = null
    },
    // 添加弹框
    open(type) {
      this.$prompt('请输入点位大类名称', '添加大类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {

        if (type === 'big') {
          this.categories.push({
            id: Date.now(),
            name: value,
            smallCategories: []
          });
        }else {
          this.activeBigCategory.smallCategories.push({
            id: Date.now(),
            name: value,
            points: []
          })
        }



        this.$message({
          type: 'success',
          message: '你的邮箱是: ' + value
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    tableRowClassName({ rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },

    convertToTree(data) {
      // 创建一个映射表，用于快速查找节点
      const nodeMap = new Map();

      // 首先将所有节点存入映射表
      data.forEach(item => {
        nodeMap.set(item.id, {
          id: item.id,
          label: item.name,
          children: []
        });
      });

      // 构建树形结构
      const tree = [];
      data.forEach(item => {
        // 获取当前节点的完整路径
        const path = item.parentRegionNode;

        // 从根节点开始构建
        let currentLevel = tree;
        for (let i = 1; i < path.length; i++) {
          const nodeId = path[i].id;
          const existingNode = currentLevel.find(n => n.id === nodeId);

          if (existingNode) {
            currentLevel = existingNode.children;
          } else {
            const newNode = {
              id: nodeId,
              label: path[i].name,
              children: []
            };
            currentLevel.push(newNode);
            currentLevel = newNode.children;
          }
        }
      });

      return tree;
    }
  },
  created() {
    // 这里可以从API获取初始数据
    // this.fetchCategories()
  }
}
</script>

<style scoped lang="scss">
.point-type-management {
  display: flex;
  height: 100vh;
}

.category-container {
  display: flex;
  width: 100%;
}

.big-category-list,
.small-category-list,
.point-list {
  padding: 20px;
  border-right: 1px solid #eee;
  height: 100%;
  overflow-y: auto;
}

.big-category-list {
  width: 200px;
}

.small-category-list {
  width: 250px;
}

.point-list {
  flex: 1;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  padding: 8px 12px;
  cursor: pointer;
  margin-bottom: 5px;
}

li:hover, li.active {
  background-color: #f0f0f0;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

button {
  margin-right: 5px;
  padding: 5px 10px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.dialog-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  .dialog-left {
    width: 20%;
    background-color: #2c3e50;
  }
  .dialog-right {
    width: 80%;
    min-height: 80vh;
    background-color: #42b983;
  }
}
</style>